package soulkun.library.component

import android.app.Activity
import android.app.Application
import android.content.Context
import soulkun.library.LibraryInit
import soulkun.library.helper.application.AppFrontBackHelper
import kotlin.collections.ArrayList

abstract class MonitorApplication : Application(), AppFrontBackHelper.OnAppStatusListener {

    protected var TAG: String? = null
    private var context: Context? = null
    private val activityList = ArrayList<Activity>()
    @Volatile
    private var isMonitorOn = false

    override fun onCreate() {
        super.onCreate()
        TAG = "TAG:" + javaClass.simpleName
        context = applicationContext
        LibraryInit(context!!)
        val appFrontBackHelper = AppFrontBackHelper(this)
        appFrontBackHelper.setOnAppStatusListener(this)
        init()
    }

    protected abstract fun init()

    fun getContext(): Context? {
        return context
    }

    @Synchronized
    fun addActivity(activity: Activity?) {
        if (activity != null) {
            activityList.add(activity)
        }
    }

    @Synchronized
    fun removeActivity(activity: Activity?) {
        if (activity != null) {
            activityList.remove(activity)
        }
    }

    @Synchronized
    fun finishAll() {
        for (activity in activityList) {
            if (!activity.isFinishing) {
                activity.finish()
            }
        }
        activityList.clear()
    }

    protected abstract fun onAppFrontIgnore(activity: Activity): Boolean

    protected abstract fun onAppBackgroundToFront(activity: Activity)

    protected abstract fun onAppFrontToBackground(activity: Activity)

    override fun onFront(activity: Activity) {
        if (!onAppFrontIgnore(activity)) {
            onAppBackgroundToFront(activity)
        }
    }

    override fun onBack(activity: Activity) {
        onAppFrontToBackground(activity)
    }

}